package com.csnf.dao.lmpl;

import com.csnf.dao.ICourseDao;
import com.csnf.entity.Course;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class CourseDaolmpl implements ICourseDao {
    @Override
    public List<Course> getAll() throws Exception {
        String path ="CourseMappe.xml";
        InputStream resourceStream = Resources.getResourceAsStream(path);
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = builder.build(resourceStream);
        List<Course>courseList;

        try (SqlSession session = sqlSessionFactory.openSession()){
            courseList = session.selectList("com.csnf.dao.ICourseDao.getAll");

        }
        return courseList;
    }

    @Override
    public Course getById(Integer id) throws Exception {
        SqlSession sqlSession = getSqlession();
        Course course = sqlSession.selectOne("com.csnf.dao.ICourseDao.getById", id);
        sqlSession.close();
        return course;
    }

    @Override
    public List<Course> getByName(String name) throws Exception {
        SqlSession sqlSession = getSqlession();
        List<Course> courseList = sqlSession.selectList("com.csnf.dao.ICourseDao.getByName", name);
        sqlSession.close();
        return courseList;
    }

    private SqlSession getSqlession() throws IOException {
        String path ="CourseMappe.xml";
        InputStream resourceStream = Resources.getResourceAsStream(path);
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = builder.build(resourceStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
    }
}
